import 'dart:math';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:talking/page/Home.dart';
import 'package:talking/page/Login.dart';
import 'package:talking/tools/config.dart';

import '../bean/bean.dart';
import '../tools/paint.dart';

class Sign extends StatefulWidget {
  @override
  SignPage createState() => SignPage();
}

class SignPage extends State<Sign> with TickerProviderStateMixin {
  List<BobbleBean> _bobbleList = [];
  Random _random = new Random(DateTime.now().microsecondsSinceEpoch);
  double _maxSpeed = 1.0;
  double _maxRadius = 100;
  double _maxTheta = 2 * pi;
  late AnimationController _animationController;
  var autoSign = true;
  var passController = TextEditingController();
  var pass2Controller = TextEditingController();
  var emailController = TextEditingController();

  var pass1Error;
  var pass2Error;
  var emailError;
  FocusNode _focus_password = FocusNode();
  FocusNode _focus_email = FocusNode();
  @override
  void initState() {
    super.initState();
    for (int i = 0; i < 20; i++) {
      BobbleBean bean = BobbleBean();
      bean.color = Color.fromARGB(_random.nextInt(200), 255, 255, 255);
      bean.offset = Offset(-1, -1);
      bean.speed = _random.nextDouble() * _maxSpeed;
      bean.radius = _random.nextDouble() * _maxRadius;
      bean.theta = _random.nextDouble() * _maxTheta;
      _bobbleList.add(bean);
    }
    _animationController =
        AnimationController(vsync: this, duration: Duration(seconds: 5));
    _animationController.addListener(() {
      setState(() {});
    });
    _animationController.repeat();
    passController.addListener(() {
      setState(() {
        pass1Error = null;
      });
    });
    pass2Controller.addListener(() {
      setState(() {
        pass2Error = null;
      });
    });
    emailController.addListener(() {
      setState(() {
        emailError = null;
      });
    });
  }

  @override
  void dispose() {
    passController.dispose();
    pass2Controller.dispose();
    emailController.dispose();
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("注册"),
      ),
      body: Stack(
        children: [
          Container(
            decoration: BoxDecoration(
                gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                  Colors.lightBlueAccent.withOpacity(0.3),
                  Colors.lightBlue.withOpacity(0.3),
                  Colors.blue.withOpacity(0.3),
                ])),
          ),
          CustomPaint(
            size: MediaQuery.of(context).size,
            painter: MyPainter(list: _bobbleList, random: _random),
          ),
          Container(
            color: Colors.white.withOpacity(0.2),
          ),
          Container(
            width: double.infinity,
            height: double.infinity,
            alignment: Alignment.bottomCenter,
            child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 30),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Padding(
                      padding: EdgeInsets.only(bottom: 10),
                      child: TextField(
                        focusNode: _focus_email,
                        controller: emailController,
                        textInputAction: TextInputAction.go,
                        decoration: InputDecoration(
                            errorText: emailError,
                            suffixIcon: InkWell(
                              child: Icon(Icons.close),
                              onTap: () {
                                emailController.clear();
                              },
                            ),
                            labelText: "请输入邮箱",
                            prefixIcon: const Icon(Icons.email),
                            border: OutlineInputBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(10)),
                            )),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(bottom: 10),
                      child: TextField(
                        controller: passController,
                        textInputAction: TextInputAction.go,
                        obscureText: true,
                        decoration: InputDecoration(
                            errorText: pass1Error,
                            suffixIcon: InkWell(
                              child: Icon(Icons.close),
                              onTap: () {
                                passController.clear();
                              },
                            ),
                            labelText: "密码",
                            prefixIcon: const Icon(Icons.lock),
                            border: OutlineInputBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(10)),
                            )),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(bottom: 10),
                      child: TextField(
                        focusNode: _focus_password,
                        controller: pass2Controller,
                        textInputAction: TextInputAction.go,
                        obscureText: true,
                        decoration: InputDecoration(
                            errorText: pass2Error,
                            suffixIcon: InkWell(
                              child: Icon(Icons.close),
                              onTap: () {
                                pass2Controller.clear();
                              },
                            ),
                            labelText: "请再次输入密码",
                            prefixIcon: const Icon(Icons.replay),
                            border: OutlineInputBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(10)),
                            )),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(bottom: 10),
                      child: ElevatedButton(
                        onPressed: () async {
                          setState(() {
                            if (passController.text.isEmpty) {
                              pass1Error = "请输入密码";
                            } else {
                              pass1Error = null;
                            }
                            if (pass2Controller.text.isEmpty) {
                              pass2Error = "请再次输入密码";
                            } else {
                              pass2Error = null;
                            }
                            if (emailController.text.isEmpty) {
                              emailError = "请输入邮箱地址";
                            } else {
                              if (Constant.isEmail(emailController.text)) {
                                emailError = null;
                              } else {
                                emailError = "邮箱格式错误";
                              }
                            }
                          });
                          if (pass1Error == null &&
                              pass2Error == null &&
                              emailError == null) {
                            if (pass2Controller.text == passController.text) {
                              var dio = Dio();
                              Map<String, dynamic> map = Map();
                              map['password'] = passController.text.toString();
                              map['email'] = emailController.text.toString();
                              var response = (await dio.post(
                                      Constant.BASE_URL + 'user/sign/',
                                      data: map))
                                  .data
                                  .toString();
                              if (response == "创建成功") {
                                SharedPreferences prefs =
                                    await SharedPreferences.getInstance();
                                await prefs.setString(
                                    'email', emailController.text);
                                await prefs.setString(
                                    'password', passController.text);
                                prefs.setBool("autoLogin", true);

                                Navigator.pop(context, "loginSuccess");
                              } else {
                                setState(() {
                                  emailError = "该邮箱已被注册";
                                });
                                FocusScope.of(context)
                                    .requestFocus(_focus_email);
                              }
                            } else {
                              setState(() {
                                pass2Error = "两次密码不一致";
                              });
                              FocusScope.of(context)
                                  .requestFocus(_focus_password);
                            }
                          }
                        },
                        child: const Text("注册"),
                        style: ButtonStyle(
                          minimumSize: MaterialStateProperty.all(
                              Size(double.infinity, 40)),
                        ),
                      ),
                    ),
                  ],
                )),
          )
        ],
      ),
    );
  }
}
